/**
 * 
 */
package com.scpii.universal.service.impl;

import java.io.File;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.dto.UserInfoDto;
import com.scpii.universal.hibernate.dao.AppDao;
import com.scpii.universal.hibernate.dao.AppIconDao;
import com.scpii.universal.hibernate.dao.AppStyleImgDao;
import com.scpii.universal.hibernate.dao.AppUpdateDao;
import com.scpii.universal.hibernate.dao.AttributeDao;
import com.scpii.universal.hibernate.dao.CatelogDao;
import com.scpii.universal.hibernate.dao.ManageUserDao;
import com.scpii.universal.hibernate.dao.SysCateAttributeDao;
import com.scpii.universal.hibernate.dao.SystemCateDao;
import com.scpii.universal.hibernate.entity.AppIconTab;
import com.scpii.universal.hibernate.entity.AppStyleImgTab;
import com.scpii.universal.hibernate.entity.AppTab;
import com.scpii.universal.hibernate.entity.AppUpdateTab;
import com.scpii.universal.hibernate.entity.AttributeTab;
import com.scpii.universal.hibernate.entity.CatelogTab;
import com.scpii.universal.hibernate.entity.SysCateAttributeTab;
import com.scpii.universal.hibernate.entity.SystemCateTab;
import com.scpii.universal.pns.dao.AppInfoDao;
import com.scpii.universal.pns.dao.FieldDao;
import com.scpii.universal.pns.entity.AppInfo;
import com.scpii.universal.pns.entity.Field;
import com.scpii.universal.pns.entity.Users;
import com.scpii.universal.service.AppService;
import com.scpii.universal.util.EhCacheManager;
import com.scpii.universal.util.FileUploadUtil;
import com.scpii.universal.util.ImgAndFilePath;

/**
 * genericWeb
 * 
 * @author weny 2012-7-8下午09:33:32
 */
@Service
public class AppServiceImpl extends BaseServiceImpl<AppTab, Integer> implements
		AppService {

	@Resource
	private AppDao appDao;
	@Resource
	private ManageUserDao manageUserDao;
	@Resource
	private AppIconDao appIconDao;
	@Resource
	private AppUpdateDao appUpdateDao;
	@Resource
	private SystemCateDao systemCateDao;
	@Resource
	private CatelogDao catelogDao;
	@Resource
	private SysCateAttributeDao sysCateAttributeDao;
	@Resource
	private AttributeDao attributeDao;
	@Resource
	private AppStyleImgDao appStyleImgDao;
	@Resource
	private FieldDao fieldDao;
	@Resource
	private AppInfoDao appInfoDao;

	private Log log = LogFactory.getLog(this.getClass());
	protected ResourceBundle bundle = ResourceBundle.getBundle(
			GenericConstants.GLOBAL_PROPERTIES_PATH, Locale.getDefault());
	private static DecimalFormat df = new DecimalFormat("##0.00");

	@Resource
	public void setBaseDao(AppDao appDao) {
		super.setBaseDao(appDao);
	}

	@Override
	public Integer save(AppTab appTab, UserInfoDto userInfo) {
		appTab.setIntEnterpId(userInfo.getIntEnterpId());// 企业ID
		appTab.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);// 逻辑删除符
		appTab.setDatUpdateDatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date()));// 更新时间
		appTab.setIntNavigatestyleId(0);// 导航风格，默认0
		Integer appId = appDao.save(appTab);
		// 更新用户应用ID
		String varPaireKey = manageUserDao.getUserInfoById(
				userInfo.getIntUserId(), new String[] { "varPaireKey" })
				.getVarPaireKey();
		StringBuffer hql = new StringBuffer("update ManageUserTab m set");
		Map<String, Object> argsMap = new HashMap<String, Object>();
		hql.append(" m.intAppId=:intAppId");
		argsMap.put("intAppId", appId);
		hql.append(" where m.intDeleteSign=:intDeleteSign");
		hql.append(" and m.varPaireKey=:varPaireKey");
		argsMap.put("intDeleteSign", GenericConstants.DELETE_SIGN_EXIST);
		argsMap.put("varPaireKey", varPaireKey);
		manageUserDao.hqlOperation(hql.toString(), argsMap);
		return appId;
	}

	/**
	 * 更新应用图标URL
	 * 
	 * @param id
	 * @param url
	 * @author liuhj 2012-7-14下午11:33:13
	 */
	private void updateIconURL(Integer id, String url) {
		StringBuffer hql = new StringBuffer("update AppIconTab a set");
		Map<String, Object> argsMap = new HashMap<String, Object>();
		hql.append(" a.datUpdateDatetime=:datUpdateDatetime");
		argsMap.put("datUpdateDatetime", new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss").format(new Date()));// date
		hql.append(",a.varIconUrl=:varIconUrl");// ICON
		argsMap.put("varIconUrl", url);
		hql.append(" where a.intIconId=:intIconId");
		argsMap.put("intIconId", id);
		appIconDao.hqlOperation(hql.toString(), argsMap);
	}

	public int[] saveApp(String json, UserInfoDto user, String webAppsRealPath,
			String imgBasePath) {
		int[] result = new int[2];
		JSONObject jo = JSONObject.fromObject(json);
		if (log.isDebugEnabled()) {
			log.debug("保存应用的json请求数据:" + jo.toString());
		}
		// 封装数据
		AppTab appTab = new AppTab();
		appTab.setVarAppName(jo.getString("varAppName"));
		appTab.setVarCountData(jo.getString("varCountData"));
		appTab.setVarAppDescript(jo.getString("varAppDescript"));
		Integer styleId = Integer.parseInt(jo.getString("intAppStyleId"));
		appTab.setIntAppStyleId(styleId == null ? 0 : styleId);
		String iconURL = jo.getString("varAppImgUrl");// icon URL
		iconURL = iconURL == null ? iconURL : iconURL.replace(getServerUrl(),
				"");
		// 保存应用
		Integer appId = this.save(appTab, user);
		// 保存icon
		Integer iconId = this.saveAppIcon(appId, iconURL);
		// 创建LOADING图片的记录，此时没有URL
		Integer loadingIconId = this
				.saveAppLoadingIcon(new AppIconTab(), appId);
		user.setAppLoadingIconId(loadingIconId);
		// 创建安卓和IOS的应用版本更新记录
		AppUpdateTab updAndroid = saveAppVersionUpdate(appId,
				GenericConstants.OPERATION_SYS_ANDROID, iconId, loadingIconId);
		AppUpdateTab updIOS = saveAppVersionUpdate(appId,
				GenericConstants.OPERATION_SYS_IOS, iconId, loadingIconId);
		user.setAndroidVersionUpdate(updAndroid);
		user.setIosVersionUpdate(updIOS);
		// 创建图片资源目录
		ImgAndFilePath.createWorkPic(webAppsRealPath, user.getIntEnterpId(),
				appId);
		if (!StringUtils.isBlank(iconURL)) {
			// 从临时文件夹复制icon到应用目录下
			String imgAbsolutePath = webAppsRealPath + imgBasePath
					+ File.separator + appId + ImgAndFilePath.ENTERP_ICON
					+ File.separator;// 绝对路径
			String targetFileName = appId + "_"
					+ GenericConstants.APP_LOGO_SUFFIX;
			String tempfilePath = webAppsRealPath
					+ iconURL.replace("/", File.separator);
			FileUploadUtil.copy(tempfilePath, imgAbsolutePath + targetFileName);
			// 更新ICON URL
			this.updateIconURL(
					iconId,
					(imgBasePath + "\\" + appId + ImgAndFilePath.ENTERP_ICON)
							.replace("\\", "/") + "/" + targetFileName);
			/*
			 * // 删除临时文件 new File(tempfilePath).delete();
			 */
		}
		// 复制系统分类及属性到分类、属性表里
		copySysCatelog(user.getIntEnterpId(), appId);
		// 复制PNS用户表字段到FIELD表
		copyUserColumns2Filed(appId);
		// pns.appinfo
		appInfoDao.save(new AppInfo((long) appId,
				"e10adc3949ba59abbe56e057f20f883e", appTab.getVarAppName()));
		result[0] = appId;
		result[1] = loadingIconId;
		return result;
	}

	private void copyUserColumns2Filed(Integer appId) {
		long uniAppId = GenericConstants.APP_ID_PRE + appId;
		for (String column : Users.COLUMNS) {
			Field obj = new Field();
			obj.setCategoriesId(16l);
			obj.setAppId(uniAppId);
			obj.setAliasName(column);
			obj.setName(column);
			if ("性别".equals(column)) {
				obj.setStatus((short) 1);
				obj.setMetaType("IMAGERADIO");
				obj.setMask("{\"required\" : true,\"optionValues\" : [ \"男\", \"女\" ],\"optionImageUrls\" : [\"http://res.gotoapp.cn/images/common/icon_boy.png\",\"http://res.gotoapp.cn/images/common/icon_girl.png\" ]}");
			} else if ("邮箱".equals(column)) {
				obj.setStatus((short) 1);
				obj.setMetaType("EMAIl");
			} else if ("电话号码".equals(column)) {
				obj.setStatus((short) 1);
				obj.setMetaType("NUMBER");
			} else if ("地址".equals(column)) {
				obj.setStatus((short) 1);
				obj.setMetaType("ADDRESS");
			} else if ("昵称".equals(column)) {
				obj.setStatus((short) 1);
				obj.setMetaType("TEXT");
			} else if ("用户名".equals(column) || "积分".equals(column)
					|| "会员等级".equals(column)) {
				obj.setStatus((short) 0);
			}
			fieldDao.save(obj);
		}
	}

	/**
	 * 复制系统分类到分类表
	 * 
	 * @param intEnterpId
	 * @param appId
	 * @author liuhj 2012-7-20下午01:43:31
	 */
	private void copySysCatelog(int intEnterpId, int appId) {
		List<SystemCateTab> lstSysCate = systemCateDao.getAll();
		if (lstSysCate == null || lstSysCate.size() <= 0) {
			return;
		}
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date());
		for (SystemCateTab systemCateTab : lstSysCate) {
			int catelogType = getCatelogType(systemCateTab.getVarSysCateName()
					.trim(), systemCateTab.getIntSysCateId());
			if (catelogType == 3) {
				if ("false".equals(EhCacheManager
						.getObject(GenericConstants.COPY_HOUSE_SYSCATELOG)))
					continue;// 不复制房产聚合
			}
			CatelogTab catelog = new CatelogTab();
			catelog.setDatUpdateDatetime(date);
			catelog.setIntAppId(appId);
			catelog.setIntEnterpId(intEnterpId);
			catelog.setVarCateName(systemCateTab.getVarSysCateName());
			catelog.setIntParentCateId(0);
			catelog.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
			catelog.setIntHasSubCate(0);
			catelog.setIntType(catelogType);
			int catelogId = catelogDao.save(catelog);

			if (log.isDebugEnabled()) {
				log.debug("复制系统分类到分类表---> ID："
						+ systemCateTab.getIntSysCateId() + " 分类名称："
						+ systemCateTab.getVarSysCateName() + " 父ID："
						+ systemCateTab.getIntParentSysCateId());
			}

			List<SysCateAttributeTab> lstAttribute = sysCateAttributeDao
					.getAttributeByCateId(systemCateTab.getIntSysCateId());
			if (lstAttribute != null && lstAttribute.size() > 0) {
				// 复制属性
				this.copySysCatelogAttribute(lstAttribute, catelogId);
			}
		}
	}

	/**
	 * 获取分类类型
	 * 
	 * @author Taylor 2012-9-19 上午09:34:44
	 * @param parentCateName
	 * @return int
	 */
	private int getCatelogType(String parentCateName, int cateId) {
		/*
		 * if (bundle.getString("sysCatelog.product").equals(parentCateName))
		 * return 0; if
		 * (bundle.getString("sysCatelog.news").equals(parentCateName)) return
		 * 1; if
		 * (bundle.getString("sysCatelog.activity").equals(parentCateName))
		 * return 2; if
		 * (bundle.getString("sysCatelog.house").equals(parentCateName)) return
		 * 3;
		 */
		return cateId - 1;
	}

	/**
	 * 复制系统属性到属性表
	 * 
	 * @param lstAttribute
	 * @param catelogId
	 * @author liuhj 2012-7-20下午02:33:47
	 */
	private void copySysCatelogAttribute(
			List<SysCateAttributeTab> lstAttribute, int catelogId) {
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date());
		for (SysCateAttributeTab sysCateAttributeTab : lstAttribute) {
			AttributeTab attribute = new AttributeTab();
			attribute.setIntCateId(catelogId);
			attribute
					.setVarAttriName(sysCateAttributeTab.getVarAttributeName());
			attribute.setDatUpdateDatetime(date);
			attribute.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
			attribute.setIntType(sysCateAttributeTab.getIntAttributeId());
			attribute.setIntInputType(getAttrInputType(sysCateAttributeTab
					.getVarAttributeName().trim()));
			attributeDao.save(attribute);

			if (log.isDebugEnabled()) {
				log.debug("复制系统分类属性到属性表---> 属性名称："
						+ sysCateAttributeTab.getVarAttributeName());
			}
		}
	}

	/**
	 * 系统属性类型
	 * 
	 * @author Taylor 2012-9-17 下午04:31:17
	 * @param parentAttrName
	 * @return int
	 */
	private int getAttrType(String parentAttrName) {
		if (bundle.getString("sysAttribute.phone_num").equals(parentAttrName))
			return 8;
		if (bundle.getString("sysAttribute.area").equals(parentAttrName))
			return 9;
		if (bundle.getString("sysAttribute.price").equals(parentAttrName))
			return 10;
		if (bundle.getString("sysAttribute.house_type").equals(parentAttrName)) // 户型
			return 11;
		return 0;
	}

	/**
	 * 系统属性输入类型
	 * 
	 * @author Taylor 2012-9-17 下午04:31:17
	 * @param parentAttrName
	 * @return int
	 */
	private int getAttrInputType(String parentAttrName) {
		if (bundle.getString("sysAttribute.area").equals(parentAttrName))
			return GenericConstants.ATTRIBUTE_INPUT_TYPE_SELECT;
		return GenericConstants.ATTRIBUTE_INPUT_TYPE_INPUT;
	}

	/**
	 * 创建LOADING的图标记录
	 * 
	 * @param appIconTab
	 * @param appId
	 * @return
	 * @author liuhj 2012-7-19下午02:43:59
	 */
	private Integer saveAppLoadingIcon(AppIconTab appIconTab, int appId) {
		// 保存LOADING
		appIconTab.setIntAppId(appId);
		if (appIconTab.getIntIconName() == null) {
			appIconTab.setIntIconName(GenericConstants.LOADING_DEFAULT_NAME);
		}
		appIconTab.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		appIconTab.setIntIconType(GenericConstants.ICON_TYPE_LOADING);
		appIconTab.setDatUpdateDatetime(new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss").format(new Date()));
		appIconTab.setIntIconDefineType(GenericConstants.ICON_DEFINE_TYPE_USER);
		Integer loadingIconId = appIconDao.save(appIconTab);
		log.info("为应用创建LOADING图片记录");
		return loadingIconId;
	}

	/**
	 * 保存版本更新记录
	 * 
	 * @param appId
	 * @param type
	 * @param iconId
	 * @param loadingIconId
	 * @return
	 * @author liuhj 2012-7-18下午05:55:09
	 */
	private AppUpdateTab saveAppVersionUpdate(int appId, int type, int iconId,
			int loadingIconId) {
		AppUpdateTab appUpd = new AppUpdateTab();
		appUpd.setIntAppId(appId);
		appUpd.setIntAppOsType(type);// 操作系统类型
		appUpd.setIntIconId(iconId);// 应用ICON
		appUpd.setIntLoadingIconId(loadingIconId);// LOADING ICON
		appUpd.setDobAppVersion(GenericConstants.APP_UPDATE_FIRST_VERSION);// VERSION
		appUpd.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		appUpd.setDatUpdateDatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date()));
		appUpd.setVarAppSign("universal" + appId);
		appUpd.setIntState(GenericConstants.APP_VERSION_UPDATE_NO);
		appUpd.setIntIsDeploy(GenericConstants.APP_VERSION_DEPLOYED_NO);
		appUpd.setIntAppSecondTitleImgId(0);
		appUpd.setIntNavBgImgId(0);
		appUpdateDao.save(appUpd);

		log.info("创建应用版本更新记录" + type);
		return appUpd;
	}

	/**
	 * 保存应用图标
	 * 
	 * @param appId
	 * @param iconURL
	 * @return
	 * @author liuhj 2012-7-18下午05:56:45
	 */
	private Integer saveAppIcon(int appId, String iconURL) {
		AppIconTab appIconTab = new AppIconTab();
		appIconTab.setIntAppId(appId);
		appIconTab.setIntIconName(GenericConstants.APP_ICON_DEFAULT_NAME);
		appIconTab.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		appIconTab.setIntIconType(GenericConstants.ICON_TYPE_APP_ICON);
		appIconTab.setDatUpdateDatetime(new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss").format(new Date()));
		appIconTab.setIntIconDefineType(GenericConstants.ICON_DEFINE_TYPE_USER);
		appIconTab.setVarIconUrl(iconURL);
		Integer iconId = appIconDao.save(appIconTab);
		return iconId;
	}

	@Override
	public void updateApp(String json, UserInfoDto user,
			String webAppsRealPath, String imgBasePath) {
		JSONObject jo = JSONObject.fromObject(json);
		if (log.isDebugEnabled()) {
			log.debug("更新应用的json请求数据:" + jo.toString());
		}
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date());
		// 风格变化，需重置用户自定义的风格
		AppTab appTab = this.getAppInfo(user.getAppId(),
				new String[] { "intAppStyleId" });
		Integer styleId = Integer.parseInt(jo.getString("intAppStyleId"));
		styleId = styleId == null ? 0 : styleId;
		AppUpdateTab androidAppUpd = user.getAndroidVersionUpdate();
		AppUpdateTab iosAppUpd = user.getIosVersionUpdate();
		if (styleId.intValue() != appTab.getIntAppStyleId().intValue()) {
			StringBuffer styleHql = new StringBuffer(
					"update AppUpdateTab a set ");
			styleHql.append("a.datUpdateDatetime=:datUpdateDatetime");
			Map<String, Object> styleMaps = new HashMap<String, Object>();
			styleMaps.put("datUpdateDatetime", date);// date
			styleHql.append(",a.intAppTitleBgImgId=:intAppTitleBgImgId");
			styleMaps.put("intAppTitleBgImgId", 0);// 标题背景
			styleHql.append(",a.intAppBackgImgId=:intAppBackgImgId");
			styleMaps.put("intAppBackgImgId", 0);// 应用背景
			styleHql.append(",a.intAppNavigateBgImgId=:intAppNavigateBgImgId");
			styleMaps.put("intAppNavigateBgImgId", 0);// 导航背景
			styleHql.append(",a.intNavBgImgId=:intNavBgImgId");
			styleMaps.put("intNavBgImgId", 0);// 导航图标点击效果
			styleHql.append(",a.intAppSecondTitleImgId=:intAppSecondTitleImgId");// 二级页面标题
			styleMaps.put("intAppSecondTitleImgId", 0);
			styleHql.append(" where a.intAppUpdateId in(");
			if (androidAppUpd != null) {
				styleHql.append(androidAppUpd.getIntAppUpdateId() + ",");
			}
			if (iosAppUpd != null) {
				styleHql.append(iosAppUpd.getIntAppUpdateId() + ",");
			}
			styleHql.deleteCharAt(styleHql.lastIndexOf(",")).append(")");
			appDao.hqlOperation(styleHql.toString(), styleMaps);
		}

		// 更新应用信息
		StringBuffer hql = new StringBuffer("update AppTab a");
		Map<String, Object> argsMap = new HashMap<String, Object>();
		hql.append(" set a.datUpdateDatetime=:datUpdateDatetime");// date
		argsMap.put("datUpdateDatetime", date);
		hql.append(",a.varAppName=:varAppName");// 名称
		argsMap.put("varAppName", jo.getString("varAppName"));
		hql.append(",a.varCountData=:varCountData");// 统计字段
		argsMap.put("varCountData", jo.getString("varCountData"));
		hql.append(",a.varAppDescript=:varAppDescript");// 描述
		argsMap.put("varAppDescript", jo.getString("varAppDescript"));
		hql.append(",a.intAppStyleId=:intAppStyleId");// 风格
		argsMap.put("intAppStyleId", styleId);
		hql.append(" where a.intAppId=:intAppId");
		argsMap.put("intAppId", user.getAppId());
		appDao.hqlOperation(hql.toString(), argsMap);
		// 获得ICON ID
		int iconId = jo.getInt("intIconId");
		String iconURL = jo.getString("varAppImgUrl");
		if (StringUtils.isBlank(iconURL)) {
			return;
		}
		iconURL = iconURL.replace(getServerUrl(), "");
		if (iconURL.lastIndexOf("?random") > 0) {
			iconURL = iconURL.substring(0, iconURL.lastIndexOf("?random"));// 去掉URL后带的随机码
		}
		String currentIconUrl = appIconDao.getIconUrlById(iconId);
		currentIconUrl = currentIconUrl == null ? currentIconUrl
				: currentIconUrl.replace(getServerUrl(), "");
		if (!iconURL.equals(currentIconUrl)) {
			// 从临时文件夹复制icon到应用目录下
			String relativePath = imgBasePath + File.separator
					+ user.getAppId() + ImgAndFilePath.ENTERP_ICON
					+ File.separator;
			String imgAbsolutePath = webAppsRealPath + relativePath;// 绝对路径
			String targetFileName = user.getAppId() + "_"
					+ GenericConstants.APP_LOGO_SUFFIX;
			String tempfilePath = webAppsRealPath
					+ iconURL.replace("/", File.separator);
			FileUploadUtil.copy(tempfilePath, imgAbsolutePath + targetFileName);
			if (StringUtils.isBlank(currentIconUrl)) {
				updateIconURL(iconId, relativePath.replaceAll("\\\\", "/")
						+ targetFileName);
			}
			// 删除临时文件
			// new File(tempfilePath).delete();
		}
		// 修改session中各种背景的ID
		if (styleId.intValue() != appTab.getIntAppStyleId().intValue()) {
			if (androidAppUpd != null) {
				androidAppUpd.setIntAppTitleBgImgId(0);
				androidAppUpd.setIntAppBackgImgId(0);
				androidAppUpd.setIntAppNavigateBgImgId(0);
				androidAppUpd.setIntAppSecondTitleImgId(0);
				androidAppUpd.setIntNavBgImgId(0);
			}
			if (iosAppUpd != null) {
				iosAppUpd.setIntAppTitleBgImgId(0);
				iosAppUpd.setIntAppBackgImgId(0);
				iosAppUpd.setIntAppNavigateBgImgId(0);
				iosAppUpd.setIntAppSecondTitleImgId(0);
				androidAppUpd.setIntNavBgImgId(0);
			}
		}
	}

	@Override
	public String getAppName(int appId) {
		return appDao.getAppInfoById(appId, new String[] { "varAppName" })
				.getVarAppName();
	}

	@Override
	public AppTab getAppInfo(int appId, String[] properties) {
		return appDao.getAppInfoById(appId, properties);
	}

	@Override
	public AppStyleImgTab getAppStyleImgById(int styleId, int type) {
		return appStyleImgDao.getStyleImgById(styleId, type);
	}

	@Override
	public void updateAppDownloadUrl(String downloadUrl, String installUrl,
			int intAppUpdateId) {
		StringBuffer hql = new StringBuffer("update AppUpdateTab a");
		Map<String, Object> argsMap = new HashMap<String, Object>();
		hql.append(" set a.datUpdateDatetime=:datUpdateDatetime");// date
		argsMap.put("datUpdateDatetime", new SimpleDateFormat(
				"yyyy-MM-dd HH:mm:ss").format(new Date()));
		hql.append(",a.varAppDownloadUrl=:varAppDownloadUrl");
		argsMap.put("varAppDownloadUrl", downloadUrl);
		if (!StringUtils.isBlank(installUrl)) {
			hql.append(",a.varIosInstallUrl=:varIosInstallUrl");
			argsMap.put("varIosInstallUrl", installUrl);
		}
		hql.append(" where a.intAppUpdateId=:intAppUpdateId");
		argsMap.put("intAppUpdateId", intAppUpdateId);
		appDao.hqlOperation(hql.toString(), argsMap);
	}

	@Override
	public AppUpdateTab saveAppVersionUpdate(UserInfoDto user, int type) {
		String[] properties = { "intIconId", "dobAppVersion",
				"intLoadingIconId", "intAppBackgImgId",
				"intAppNavigateBgImgId", "intAppTitleBgImgId", "intNavBgImgId",
				"intAppSecondTitleImgId" };
		// 应用最新版本的信息
		AppUpdateTab lastAppUpd = appUpdateDao.getVersionUpdateInfo(
				user.getAppId(), properties, type);
		AppUpdateTab appUpd = new AppUpdateTab();
		appUpd.setIntAppId(user.getAppId());
		appUpd.setIntAppOsType(type);// 操作系统类型
		appUpd.setIntIconId(lastAppUpd.getIntIconId());// 应用ICON
		int d = (int)(Math.round(lastAppUpd.getDobAppVersion()*100)) + 1;
		appUpd.setDobAppVersion(Double.valueOf(df.format(d/100.0)));// VERSION
		appUpd.setIntDeleteSign(GenericConstants.DELETE_SIGN_EXIST);
		appUpd.setDatUpdateDatetime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date()));
		appUpd.setVarAppSign("universal" + user.getAppId());
		appUpd.setIntLoadingIconId(lastAppUpd.getIntLoadingIconId());
		appUpd.setIntAppBackgImgId(lastAppUpd.getIntAppBackgImgId());
		appUpd.setIntAppNavigateBgImgId(lastAppUpd.getIntAppNavigateBgImgId());
		appUpd.setIntAppTitleBgImgId(lastAppUpd.getIntAppTitleBgImgId());
		appUpd.setIntNavBgImgId(lastAppUpd.getIntNavBgImgId());
		appUpd.setIntAppSecondTitleImgId(lastAppUpd.getIntAppSecondTitleImgId());
		appUpd.setIntState(GenericConstants.APP_VERSION_UPDATE_NO);
		appUpd.setIntIsDeploy(GenericConstants.APP_VERSION_DEPLOYED_NO);
		appUpdateDao.save(appUpd);
		log.info("创建应用版本更新记录" + type);
		return appUpd;
	}

	@Override
	public boolean checkIfCanproduceApp(UserInfoDto user) {
		return appDao.getTotalCount(user.getAppId()) > 0 ? true : false;
	}

	@Override
	public void updateVersionState(AppUpdateTab appUpd, int state) {
		if (state == GenericConstants.APP_VERSION_UPDATE_NO) {
			return;
		}
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
				.format(new Date());
		StringBuffer hql = new StringBuffer("update AppUpdateTab a");
		Map<String, Object> argsMap = new HashMap<String, Object>();
		hql.append(" set a.datUpdateDatetime=:datUpdateDatetime");// date
		argsMap.put("datUpdateDatetime", date);
		hql.append(",a.intState=:intState");
		argsMap.put("intState", state);
		hql.append(",a.intIsDeploy=:intIsDeploy");
		argsMap.put("intIsDeploy", GenericConstants.APP_VERSION_DEPLOYED_YES);
		hql.append(" where a.intAppUpdateId=:intAppUpdateId");
		argsMap.put("intAppUpdateId", appUpd.getIntAppUpdateId());
		appDao.hqlOperation(hql.toString(), argsMap);
		// 更新以前的版本状态
		StringBuffer hqlBefore = new StringBuffer("update AppUpdateTab a");
		Map<String, Object> mapsBefore = new HashMap<String, Object>();
		hqlBefore.append(" set a.intState=:intState");
		mapsBefore.put("intState", GenericConstants.APP_VERSION_UPDATE_NO);
		hqlBefore.append(" where a.intAppUpdateId!=:intAppUpdateId");
		mapsBefore.put("intAppUpdateId", appUpd.getIntAppUpdateId());
		hqlBefore
				.append(" and a.intAppOsType=:intAppOsType and a.intAppId=:intAppId");
		mapsBefore.put("intAppOsType", appUpd.getIntAppOsType());
		mapsBefore.put("intAppId", appUpd.getIntAppId());
		appDao.hqlOperation(hqlBefore.toString(), mapsBefore);
	}

	@Override
	public void updateIosCerFile(String jsonData, int appId) {
		JSONArray ja = JSONArray.fromObject(jsonData);
		String varAppstoreCerUrl = "";
		String varGotoappCerUrl = "";
		int size = ja.size();
		for (int i = 0; i < size; i++) {
			JSONObject jo = ja.getJSONObject(i);
			String flag = jo.getString("flag");
			String url = jo.getString("url").replace(getServerUrl(), "");
			if ("appStore_cer".equals(flag)) {
				varAppstoreCerUrl = url + ";" + varAppstoreCerUrl;
			} else if ("appStore_pro".equals(flag)) {
				varAppstoreCerUrl = varAppstoreCerUrl + url;
			} else if ("gotoapp_cer".equals(flag)) {
				varGotoappCerUrl = url + ";" + varGotoappCerUrl;
			} else if ("gotoapp_pro".equals(flag)) {
				varGotoappCerUrl = varGotoappCerUrl + url;
			}
		}
		if ((varAppstoreCerUrl == null || !varAppstoreCerUrl.contains(";"))
				&& (varGotoappCerUrl == null || !varGotoappCerUrl.contains(";")))
			return;
		StringBuffer hql = new StringBuffer("update AppTab a set ");
		Map<String, Object> argsMap = new HashMap<String, Object>();
		if (varAppstoreCerUrl != null && varAppstoreCerUrl.contains(";")) {
			hql.append("a.varAppstoreCerUrl=:varAppstoreCerUrl,");
			argsMap.put("varAppstoreCerUrl", varAppstoreCerUrl);
		}
		if (varGotoappCerUrl != null && varGotoappCerUrl.contains(";")) {
			hql.append("a.varGotoappCerUrl=:varGotoappCerUrl,");
			argsMap.put("varGotoappCerUrl", varGotoappCerUrl);
		}
		hql.deleteCharAt(hql.lastIndexOf(","));
		hql.append(" where a.intAppId=:intAppId");
		argsMap.put("intAppId", appId);
		appDao.hqlOperation(hql.toString(), argsMap);
	}
}
